<?php
/**
 * author:歪妻
 * Date: 2020/10/31 0031
 */

require_once 'lib/common.php';
require_once 'lib/install.php';
//我们将内容存储在会话中，以免重定向到self
session_start();
// 仅在我们响应表单时运行安装程序
if ($_POST)
{
    // 这是安装 删除硬连接的方式
    $pdo = getPDO();
    list($rowCounts, $error) = installBlog($pdo);
    $password = '';
    if (!$error)
    {
        $username = 'admin';
        list($password, $error) = createUser($pdo, $username);
    }
    $_SESSION['count'] = $rowCounts;
    $_SESSION['error'] = $error;
    $_SESSION['username'] = $username;
    $_SESSION['password'] = $password;
    $_SESSION['try-install'] = true;
    //...在这里，我们从POST重定向到GET
    redirectAndExit('install.php');

}
// 让我们看看是否已经安装
$attempted = false;
if (isset($_SESSION['try-install']))
{
    $attempted = true;
    $count = $_SESSION['count'];
    $error = $_SESSION['error'];
    $username = $_SESSION['username'];
    $password = $_SESSION['password'];

    // 未设置会话变量，因此我们只报告一次安装/失败
    unset($_SESSION['count']);
    unset($_SESSION['error']);
    unset($_SESSION['username']);
    unset($_SESSION['password']);
    unset($_SESSION['try-install']);
}

?>
<!DOCTYPE html>
<html>
<head>
    <title>Blog installer</title>
    <?php require "templates/head.php"?>
</head>
<body>
<?php if ($attempted): ?>
    <?php if ($error): ?>
        <div class="error box">
            <?php echo $error ?>
        </div>
    <?php else: ?>
        <div class="success box">
            数据库和演示数据创建成功。
            <?php //报告每个表的计数 ?>
            <?php foreach (array('post', 'comment') as $tableName): ?>
                <?php if (isset($count[$tableName])): ?>
                    <!--几条数据-->
                    <?php echo $count[$tableName] ?> 条
                    <!--数据表名 ?-->
                    <?php echo $tableName ?>s
                    创建成功.
                <?php endif ?>
            <?php endforeach ?>
            <?php //报告新密码 ?>
            账户名是 '<?php echo htmlEscape($username) ?>' 密码是
            <span class="install-password"><?php echo htmlEscape($password) ?></span>
            (如果需要，将其复制到剪贴板).
        </div>
        <p>
            <a href="index.php">首页</a>,
            or <a href="install.php">重新安装</a>.
        </p>
    <?php endif ?>
<?php else: ?>
    <p>点击这里创建数据库.</p>
    <form method="post">
        <input name="install" type="submit" value="安装"/>
    </form>
<?php endif ?>
</body>
</html>